Spinner提供一種方法,可以讓使用者從數據集合中快速選擇一個值
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/what"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="今晚你想吃什麼?"
android:textSize="20sp" />
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
回到MainActivity
package com.example.spinner;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//宣告物件
private Spinner spinner;
private String[] dinner ={"鐵板燒","鍋燒意麵","拉麵","炒飯","蛋包飯","漢堡薯條","牛排"};// 建立資料來源
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
Useadapter();
setSpinner();
}
private void setSpinner() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String food =parent.getItemAtPosition(position).toString();
Toast.makeText(MainActivity.this, "我想吃:" + food, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void Useadapter() {
ArrayAdapter<String> dinnerList = new ArrayAdapter<>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,dinner);// 建立Adapter並且連結資料來源
spinner.setAdapter(dinnerList);//連結 Adapter到控制元件
}
private void init() {
spinner= findViewById(R.id.spinner);
}
}
onItemSelected:當使用者選中Spinner選項時所執行的方法,那onNothingSelected則是當使用者沒選中Spinner選項時所執行的方法